package reference;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

public class SoftReferenceCache<K, V> {
    private final Map<K, SoftReference<V>> cache = new HashMap<>();

    public V get(K key) {
        SoftReference<V> ref = cache.get(key);
        if (ref != null) {
            V value = ref.get();
            if (value != null) {
                return value;
            } else {
                cache.remove(key);
            }
        }
        return null;
    }

    public void put(K key, V value) {
        cache.put(key, new SoftReference<>(value));
    }

    public static void main(String[] args) {
        SoftReferenceCache<String, String> cache = new SoftReferenceCache<>();
        cache.put("key1", "value1");
        cache.put("key2", "value2");

        System.out.println(cache.get("key1")); // 输出：value1
        System.out.println(cache.get("key2")); // 输出：value2

        // 模拟内存不足，触发垃圾收集
        byte[] array = new byte[10 * 1024 * 1024];

        System.out.println(cache.get("key1")); // 可能输出：null
        System.out.println(cache.get("key2")); // 可能输出：null
    }
}
